#include "../../common/detail.hpp"
#include "../../common/net.hpp"
#include "../../common/dispatcher.hpp"
#include "../../server/rpc_router.hpp"
#include "../../client/requestor.hpp"
#include "../../client/rpc_caller.hpp"

void callback(const Json::Value &result) {
    ILOG("callback result: %d", result.asInt());
}

int main()
{
    auto requestor = std::make_shared<yfrpc::client::Requestor>();
    auto caller = std::make_shared<yfrpc::client::RpcCaller>(requestor);
    auto dispatcher = std::make_shared<yfrpc::Dispatcher>();
    auto rsp_cb = std::bind(&yfrpc::client::Requestor::onResponse, requestor.get(),
        std::placeholders::_1, std::placeholders::_2);
    dispatcher->registerHandler<yfrpc::BaseMessage>(yfrpc::MType::RSP_RPC, rsp_cb);

    auto client = yfrpc::ClientFactory::create("127.0.0.1", 9090);
    auto message_cb = std::bind(&yfrpc::Dispatcher::onMessage, dispatcher.get(),
        std::placeholders::_1, std::placeholders::_2);
    client->setMessageCallback(message_cb);
    client->connect();
    auto conn = client->connection();

    Json::Value params, result;
    params["num1"] = 11;
    params["num2"] = 22;
    bool ret = caller->call(conn, "Add", params, result);
    if (ret != false) {
        ILOG("result: %d", result.asInt());
    }


    yfrpc::client::RpcCaller::JsonAsyncResponse res_future;
    params["num1"] = 33;
    params["num2"] = 44;
    ret = caller->call(conn, "Add", params, res_future);
    if (ret != false) {
        result = res_future.get();
        ILOG("result: %d", result.asInt());
    }


    params["num1"] = 55;
    params["num2"] = 66;
    ret = caller->call(conn, "Add", params, callback);
    if (ret != false) {
        result = res_future.get();
        ILOG("result: %d", result.asInt());
    }
    std::this_thread::sleep_for(std::chrono::seconds(1));
    client->shutdown();

    return 0;

}